package com.github.chirspan.xaas.security.util;

import com.github.chirspan.xaas.security.service.AuthUserDetail;
import com.github.chirspan.xaas.rbac.model.RbacUser;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.HashSet;
import java.util.Set;

/**
 * @author ChenPan
 * @date 2018/6/25 13:54
 * description:
 */
public final class SecurityUtils {

    /**
     * 获取当前用户的用户名
     *
     * @return
     */
    public static String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = null;
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            currentUserName = authentication.getName();

        }
        return currentUserName;
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    public static AuthUserDetail getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof AnonymousAuthenticationToken) {
            RbacUser tmpUser = new RbacUser();
            tmpUser.setUsername(authentication.getPrincipal().toString());
            return new AuthUserDetail(tmpUser, null);
        } else {
            return (AuthUserDetail) authentication.getPrincipal();
        }
    }

    public static Set<String> getAuthorities() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Set<String> authorities = new HashSet<>();
        authentication.getAuthorities().stream().forEach(a -> authorities.add(((GrantedAuthority) a).getAuthority()));

        return authorities;
    }

    /**
     * 当前用户是否拥有权限
     *
     * @param role
     * @return
     */
    public static boolean hasRole(String role) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return false;
        }

        for (GrantedAuthority auth : authentication.getAuthorities()) {
            if (role.equalsIgnoreCase(auth.getAuthority())) {
                return true;
            }
        }

        return false;
    }

    /**
     * 获取用户权限
     */
    public static Set<String> getUserAuth() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Set<String> authorities = new HashSet<>();
        authentication.getAuthorities().forEach(a -> authorities.add(((GrantedAuthority) a).getAuthority()));

        return authorities;
    }
}
